<?php
/**
 * Created by Netbeans.
 * User: PuLinGao
 * Date: 2014/11/11
 * Time: 23:20
 * 网点管理
 */

class NetworkController extends AdminController{
    private $pagesize = 15;
    /**
     * 银行列表
     */
    public function actionBank()
    {
        $p = $this->get('p', 1);
        $criteria = new CDbCriteria();
        $count = NetworkBank::model()->count($criteria);
        $criteria->limit = $this->pagesize;
        $criteria->offset = ($p -1) * $this->pagesize;
        $data = NetworkBank::model()->findAll($criteria);
        
        $page = new Page($count, $criteria->limit); 
        $this->smarty->assign('pages', $page->style1());
        $this->smarty->assign('list', $data);
        $this->smarty->display('network/bank.tpl');
    }
    /**
     * 添加银行
     */
    public function actionAddBank(){
        $this->smarty->display('network/addbank.tpl');
    }
    /**
     * 处理添加银行
     */
    public function actionDoAddBank(){
        $bank = new NetworkBank();
        $bank->bank_name = $this->post('bank_name');
        $bank->domain = strtolower($this->post('domain'));
        $bank->background = $this->post('background');
        $bank->logo = $this->post('logo');
        //判断域名和银行是否存在
        if ($bank->findByDomain($bank->domain)) {
            $this->jump('域名已经存在');
        }
        if ($bank->findByBank($bank->bank_name)) {
            $this->jump('银行名称已经存在');
        }
        
        if ($bank->save()) {
            $this->jump('添加成功', '/webadmin/network/bank');
        } else {
            $this->jump('添加失败');
        }
    }
    /**
     * 编辑银行
     */
    public function actionEditBank(){
        $bank_id = $this->get('bank_id');
        $bank = new NetworkBank();
        $info = $bank->findByPk($bank_id);
        $this->smarty->assign('info', $info);
        $this->smarty->display('network/addbank.tpl');
    }
    /**
     * 处理编辑银行
     */
    public function actionDoEditBank(){
        $bank = new NetworkBank();
        $data['bank_name'] = $this->post('bank_name');
        $data['domain'] = $this->post('domain');
        $data['background'] = $this->post('background');
        $data['logo'] = $this->post('logo');
        $bank_id = (int)$this->post('bank_id');
        $res = $bank->updateByPk($bank_id, $data);
        if ($res) {
            $this->jump('修改成功', '/webadmin/network/bank');
        } else {
            $this->jump('修改失败');
        }
    }
    /**
     * 删除银行
     */
    public function actionDelbank(){
        $bank_id = (int)$this->get('bank_id');
        if (NetworkBank::model()->deleteByPk($bank_id)) {
            $this->_ajax(array('status' => 1, 'note' => '删除成功'));
        } else {
            $this->_ajax(array('status' => 0, 'note' => '删除失败'));
        }
    }
    /**
     * 删除logo
     */
    public function actionDelLogo(){
        $bank_id = (int)$this->get('bank_id');
        $type = $this->get('type');
        if ($type == 'logo') {
            $res = NetworkBank::model()->updateByPk($bank_id,array('logo' => ''));
        } else {
            $res = NetworkBank::model()->updateByPk($bank_id,array('background'=>''));
        }
        if ($res) {
            $this->_ajax(array('status' => 1, 'note' => '删除成功'));
        } else {
            $this->_ajax(array('status' => 0, 'note' => '删除失败'));
        }
        
    }
    /**
     * 银行上传网点附件
     * 网点编号-文件序号.后缀
     * 需要解压上传到每个网点下
     */
    public function actionUpAttach()
    {
        $bank_id = $this->get('bank_id');
        //银行信息
        $bank_info = NetworkBank::model()->findByPk($bank_id)->attributes;
        $this->smarty->assign('bank_info', $bank_info);
        $criteria = new CDbCriteria();
        $criteria->addColumnCondition(array('bank_id' => $bank_id));
        $criteria->order = 'create_time desc';
        $criteria->limit = 10;
        $list = NetworkBankZip::model()->findAll($criteria);
        $this->smarty->assign('list', $list);
        $this->smarty->assign('bank_id', $bank_id);
        $this->smarty->display('network/upattach_new.tpl');
    }
    /**
     * 删除银行附件
     */
    public function actionDelBankAttach()
    {
        $nba_id = (int)$this->get('nba_id');
        if (NetworkBankZip::model()->deleteByPk($nba_id)) {
            //同时删除网点附件表
            NetworkAttach::model()->updateAll(array('status' => 0),'nba_id=:nba_id', array(':nba_id' => $nba_id));
            $this->_ajax(array('status' => 1,'note' => '删除成功'));
        } else {
            $this->_ajax(array('status' =>0,'note' => '删除失败'));
        }
    }
    /**
     * 网点列表
     */
    public function actionList(){
        $p = $this->get('p', 1);
        $network_name = $this->get('network_name');
        $network_num = $this->get('network_num');
        $up_network_id = (int)$this->get('up_network_id');
        $bank_id = (int)$this->get('bank_id');
		$level = (int)$this->get('level');
        $criteria = new CDbCriteria();
        if ($bank_id) {
            $criteria->addColumnCondition(array('bank_id' => $bank_id));
        }
        if ($network_name) {
            $criteria->addColumnCondition(array('network_name' => $network_name));
        }
        if ($network_num) {
            $criteria->addColumnCondition(array('network_num' => $network_num));
        }
        if ($up_network_id) {
            $criteria->addColumnCondition(array('up_network_id' => $up_network_id));
        }
		if ($level) {
			$criteria->addColumnCondition(array('level' => $level));
		}
        $count = NetWork::model()->count($criteria);

        $criteria->limit = $this->pagesize;
        $criteria->offset = ($p - 1) * $this->pagesize;
        $criteria->order = 'network_id DESC';
        $data = NetWork::model()->findAll($criteria);
        $page = new Page($count, $criteria->limit);   

        $this->smarty->assign('level', NetWork::networkLevel());
        $this->smarty->assign('network_name', $network_name);
        $this->smarty->assign('network_num', $network_num);
        $this->smarty->assign('page', $page->style1());
        $this->smarty->assign('list', $data);
        $this->smarty->assign('banklist', NetworkBank::model()->getKv());
		$this->smarty->assign('level', NetWork::networkLevel());
        $this->smarty->assign('bank_id', $bank_id);
		$this->smarty->assign('select_level', $level);
        $this->smarty->display("network/list.tpl");
    }
    /**
     * 异步获取银行网点，支行以上级别
     */
    public function actionGetNet(){
        $up_network_id = (int)$this->get('up_network_id');
        $network = new NetWork();
        $list = $network->getLevel($up_network_id, Network::NETWORK_LEVEL_TWO);
        //如果二级没有这查找三级
        if (!$list) {
           $list = $network->getLevel($up_network_id, Network::NETWORK_LEVEL_THREE); 
        }
        $this->_ajax(array('status' => 1, 'data' => $list));
    }

    /**
     * 添加网点页面
     */
    public function actionAdd(){
        $up_network_id = $this->get('up_network_id', 0);
		//找到此上级网点信息
		$info = NetWork::model()->findByPk($up_network_id)->attributes;
		$this->smarty->assign('bank_id', $info['bank_id']);
		$this->smarty->assign('next_level', $info['level']+1);
		
        $this->smarty->assign('banklist', NetworkBank::model()->getKv());
		$alllevel = NetWork::networkLevel();
		unset($alllevel[NetWork::NETWORK_LEVEL_FIVE]);
        $this->smarty->assign('alllevel', $alllevel);
        $this->smarty->assign('up_network_id', $up_network_id);
        $this->smarty->display("network/add.tpl");
    }
    /**
     * 检查网点编号是否已经存在
     */
    public function actionCheckNetwork(){
        $network_num = $this->get('network_num');
        if (NetWork::model()->find('network_num="'.$network_num.'"')){
            $this->setreturn(0, '网点编号已经存在');
        } else {
           $this->setreturn(1); 
        }
        $this->_ajax();
    }

    /**
     * 处理添加
     */
    public function actionDoAdd(){
        $networkModel = new NetWork();
        $networkModel->network_num = $this->post('network_num');
        $networkModel->network_name = $this->post('network_name');
        $networkModel->network_username = $this->post('network_username');
        $networkModel->network_pwd = $this->post('network_pwd');
        $networkModel->bank_id = (int)$this->post('bank_id');
        $networkModel->level = (int)$this->post('level');
        $networkModel->auth_grade = (int)$this->post('auth_grade');
        $networkModel->up_network_id = (int)$this->post('up_network_id');

        $networkModel->create_time = time();
        $networkModel->update_time = time();
        $networkModel->user_id = $this->user_id ? $this->user_id :0;

        //根据银行和网点编号，判断编号是否存在
        if (NetWork::model()->find('bank_id = '.$networkModel->bank_id.' and network_num="'.$networkModel->network_num.'"')){
            $this->jump('此银行下已存在编号为'.$networkModel->network_num.'的网点');
        }
        
        $res = $networkModel->save();
        if ($res) {
            $this->jump('添加成功', '/webadmin/network/list');
        } else {
            $this->jump('添加失败');
        }
    }
	
    /**
     * 编辑
     */
    public function actionEdit(){
        $networkId = $this->get('network_id');

        $networkModel = new NetWork();
        $info = $networkModel->findByPk($networkId);

        $this->smarty->assign('info', $info);
        $this->smarty->assign('banklist', NetworkBank::model()->getKv());
        $alllevel = NetWork::networkLevel();
		unset($alllevel[NetWork::NETWORK_LEVEL_FIVE]);
        $this->smarty->assign('alllevel', $alllevel);
        $this->smarty->assign('up_network_id', $info['up_network_id']);
        $this->smarty->display('network/add.tpl');
    }
	
    /**
     * 处理编辑
     */
    public function actionDoEdit(){
        $networkId = (int)$this->post('network_id');
        //查询旧数据
        $networkModel = new NetWork();
        $info = $networkModel->findByPk($networkId);
        # 获取post值
        $data['network_name'] = $this->post('network_name');
        $data['network_num'] = $this->post('network_num');
        $data['network_username'] = $this->post('network_username');
        $data['network_pwd'] = $this->post('network_pwd');
        //修改密码
        if ($info['network_pwd'] != $data['network_pwd']) {
            //$data['network_pwd'] = $info['network_pwd'];
        }
        $data['auth_grade'] = $this->post('auth_grade');
        $data['bank_id'] = $this->post('bank_id');
        $data['level'] = $this->post('level');
        $data['up_network_id'] = $this->post('up_network_id');

        $data['update_time'] = time();
        $data['user_id'] = $this->user_id ? $this->user_id : 0;

        
        $res = $networkModel->updateByPk($networkId,$data);
        
        if ($res) {
            $this->jump('修改成功', '/webadmin/network/list');
        } else {
            $this->jump('修改失败');
        }
    }
	
    /**
     * 删除网点
     */
    public function actionDelete(){
        $networkId = (int)$this->post('network_id');

        $networkModel = new NetWork();
        $res = $networkModel->deleteByPk($networkId);

        if($res){
            $this->_ajax(array('status' => 1,'note' => '删除成功'));
        }else{
            $this->_ajax(array('status' => 0,'note' => '删除失败'));
        }
    }
	
    /**
     * 网点用户管理
     * 没用
     */
    public function actionUser(){
        $p = $this->get('p', 1);

        $criteria = new CDbCriteria();
        $count = NetWork::model()->count($criteria);

        $criteria->limit = $this->pagesize;
        $criteria->offset = ($p - 1) * $this->pagesize;
        $criteria->order = 'network_id DESC';
        $data = NetWork::model()->findAll($criteria);
        $page = new Page($count, $this->pagesize);

        $this->smarty->assign('level', NetWork::networkLevel());
        $this->smarty->assign('page', $page->style1());
        $this->smarty->assign('list', $data);
        $this->smarty->display("network/user.tpl");
    }
    /**
     * 网点信息导入--具体网点
     */
    public function actionImport()
    {
        $this->smarty->assign('banklist', NetworkBank::model()->getKv());
        $this->smarty->display('network/import.tpl');
    }
	
	//模板下载
	public function actionTemplateDown() {
		header("Content-type: application/octet-stream");
		header("Accept-Ranges: bytes");
                header("Content-Type:application/force-download");
                header("Content-Transfer-Encoding:binary");
                header('Content-Type: application/vnd.ms-excel; charset=utf-8'); 
                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header("Content-Disposition:attachment;filename=".urlencode('网点导入模板').".xlsx");
		readfile(dirname(Yii::app()->BasePath).'/assets/import_template/network_import.xlsx');
		exit;
	}

    /**
     * 导入
     * excel
     */
    public function actionDoImport(){
		$bank_id = $this->post('bank_id');
		
		$modelQuesNetworkImport = new QuestionNetworkImportModel();
        $upload = new Uploader();
		$config = array(
			'new_name' => 'network_template',
			'allow_ext' => 'xls,xlsx',
			'save_path' => dirname(Yii::app()->basePath) . '/assets/question_network/',
			'allow_max_size' => 8000000
		);
		$upload->init($config);
		if ($upload->check()) {
			$uploadFilePath = $upload->up();

			//解析网点excel的内容
			try {
				
				// 自定义错误类型，友好提示用户
				ini_set('display_errors', 'Off');
				register_shutdown_function(function() {
					$last_error = error_get_last();
					if ($last_error['type'] === E_ERROR) {
						call_user_func('customError', '');
					}
				});
				
				$this->enablePHPExcel();
				$questionImport = new QuestionExcel();
				$type = explode('.', $uploadFilePath);
				$message = $questionImport->questionNetworkImport($uploadFilePath, $type[1]);
			} catch (Exception $exc) {
				$error[] = $exc->getMessage();
			}
			if (!empty($error)) {
				$this->jump(join(' | ', $error));
			}

			//处理解析数据(提示)
			$modelQuesNetworkImport->formatExcelData($message['msg'], $bank_id);
			$formatError = $modelQuesNetworkImport->getError();
			if (!empty($formatError)) {
				$this->smarty->assign('project_id', $project_id);
				$this->smarty->assign('error', $formatError);
				$this->smarty->display('network/import_error.tpl');
				exit;
			}

			$this->jump('导入成功', '/webadmin/network/list');
			
		} else {
			# 上传验证不通过，提示原因
			$this->jump($upload->geterror());
		}
    }
    /**
     * 导出弹层
     */
    public function actionExport(){
		$this->smarty->assign('banklist', NetWork::model()->getLevel(0, NetWork::NETWORK_LEVEL_ONE));
        $this->smarty->display('network/export.tpl');
    }
    /**
     * 网点信息导出
     */
    public function actionDoExport(){
        $bank_id = $this->post('bank_id');//其实为总行ID
        $up_network_id = $this->post('up_network_id');
        $criteria = new CDbCriteria();
        $networkModel = new NetWork();
        $data = array();
        $up_network_second = array();

        # 指定分行
        if ($up_network_id) {
                $criteria->addCondition('up_network_id = ' . $up_network_id);
        } else {//否则未总行，那么直接查银行即可
                if ($bank_id) {
                    $info = NetWork::model()->findByPk($bank_id)->attributes;
                    $bank_id = $info['bank_id'];
                    $criteria->addColumnCondition(array('bank_id'=> $bank_id));
                }
        }

        $data = $networkModel->findAll($criteria);
        $datas = $networkModel->listNetwork($data);
        if (empty($datas)) {
                $this->jump('暂时无下级网点信息');
        }
        $this->enablePHPExcel();
        $networkExcel = new NetworkExcel();
        $networkExcel->networkExport($datas);
    }
    /**
     * 网点附件
     */
    public function actionAttach(){
        $p = $this->get('p', 1);
        $network_id = $this->get('network_id');
        $this->smarty->assign('network_id', $network_id);
        //列出已有附件
        $netattach = new NetworkAttach();
        $criteria = new CDbCriteria();
        $criteria->addColumnCondition(array('network_id' => $network_id));
        $criteria->addColumnCondition(array('status' => 1));
        $total = $netattach->count($criteria);
        $criteria->limit = 5;
        $criteria->offset = ($p - 1) * 5;
        $criteria->order = 'create_time desc';
        $list = $netattach->findAll($criteria);

        $page = new Page($total, 5);
        $this->smarty->assign('list', $list);
        $this->smarty->assign('page', $page->style1());
        $this->smarty->display('network/attach_new.tpl');
    }
    /**
     * 网点通用附件
     */
    public function actionCommonAttach()
    {
        $bank_id = $this->get('bank_id');
        $this->smarty->assign('bank_id', $bank_id);
        $this->smarty->display('network/commonattach.tpl');
    }
    /**
     * 删除网点附件
     */
    public function actionDelAttach()
    {
        $na_id = (int)$this->get('na_id');
        $networkModel = new NetworkAttach();
        $res = $networkModel->deleteByPk($na_id);

        if($res){
            $this->_ajax(array('status' => 1,'note' => '删除成功'));
        }else{
            $this->_ajax(array('status' => 0,'note' => '删除失败'));
        }
    }
    /**
     * 网点报备开通
     */
    public function actionReport(){
        $network_id = (int)$this->get('network_id');
        $up_network_id = (int)$this->get('up_network_id');
        $report = (int)$this->get('report');
        $note = $report ==1 ? '开通报备成功' : '关闭报备成功';
        if (NetWork::model()->updateByPk($network_id, array('open_report' => $report))) {
            if ($report == 1) {//开通
                //如果是总行开通，下面银行都开通
                if ($up_network_id == 0) {
                    $info = NetWork::model()->findByPk($network_id)->attributes;
                    $bank_id = $info['bank_id'];
                    NetWork::model()->updateAll(array('open_report' => 1),'bank_id=:bank_id',array(':bank_id' => $bank_id)); 
                } else {
                    //查上级
                    $up_info = NetWork::model()->find('network_id='.$up_network_id);
                    NetWork::model()->updateAll(array('open_report' => 1),'network_id=:network_id',array(':network_id' => $up_network_id));
                    if ($up_info['up_network_id']) {
                        $up_up_network_id = $up_info['up_network_id'];
                        $up_up_info = NetWork::model()->find('network_id='.$up_up_network_id);
                        NetWork::model()->updateAll(array('open_report' => 1),'network_id=:network_id',array(':network_id' => $up_up_network_id));
                    }
                    if ($up_up_info && $up_up_info['up_network_id']) {
                        NetWork::model()->updateAll(array('open_report' => 1),'network_id=:network_id',array(':network_id' => $up_up_info['up_network_id']));
                    } 
                }
            } else {
                if ($up_network_id == 0) {
                    $info = NetWork::model()->findByPk($network_id)->attributes;
                    $bank_id = $info['bank_id'];
                    NetWork::model()->updateAll(array('open_report' => 0),'bank_id=:bank_id',array(':bank_id' => $bank_id)); 
                } else {
                    //查上级
                    $up_info = NetWork::model()->find('network_id='.$up_network_id);
                    NetWork::model()->updateAll(array('open_report' => 0),'network_id=:network_id',array(':network_id' => $up_network_id));
                    if ($up_info['up_network_id']) {
                        $up_up_network_id = $up_info['up_network_id'];
                        $up_up_info = NetWork::model()->find('network_id='.$up_up_network_id);
                        NetWork::model()->updateAll(array('open_report' => 0),'network_id=:network_id',array(':network_id' => $up_up_network_id));
                    }
                    if ($up_up_info && $up_up_info['up_network_id']) {
                        NetWork::model()->updateAll(array('open_report' => 0),'network_id=:network_id',array(':network_id' => $up_up_info['up_network_id']));
                    }  
                }
            }
            $this->_ajax(array('status' => 1,'note' => $note));
        } else {
            $this->_ajax(array('status' => 0,'note' => '操作失败'));
        }
    }
    /**
     * 开通一个银行下面所有网点报备
     */
    public function actionOpenBaobei()
    {
        $bank_id = (int)$this->get('bank_id');
        if (NetWork::model()->updateAll(array('open_report' => 1),'bank_id=:bank_id',array(':bank_id' => $bank_id)))
        {
            $this->_ajax(array('status' => 1,'note' => '开通报备成功'));
        } else {
            $this->_ajax(array('status' => 0,'note' => '操作失败'));
        }
    }
}
